
import { response } from 'express';
// user
const { controller,httpGet, httpPost}  = require('inversify-express-utils')//注入器
import { UserService } from './servers'
import {inject} from 'inversify'
import type { Request,Response } from 'express'
import { JWT } from '../../jwt';

@controller('/user')
export class User{
    constructor(@inject(UserService) private readonly userService:UserService){}
    @httpGet('/index')
    public async getIndex(req:Request,res:Response){
        console.log(req.query);
        let result = await this.userService.getUser() //注意异步的传染性
        res.send(result)
    }

    @httpGet('/token',JWT.middleware())  //假如必须携带有效token
    public async getToken(req,res){
        console.log("token中的user（req.user）:",req.user.id);// 打印出token(如果token里载荷user就可以直接读出了)  要.id出来记得扩展接口
        // console.log(req.query);
        let result = await this.userService.getUserToken() //注意异步的传染性
        res.send(result)
    }

    @httpPost('/create')
    public async createUser(req:Request,res:Response){
        console.log("req.body:",req.body);

        // if (!req.body) {
        //     return res.status(400).send({ error: 'Missing request body' });
        // }

        try {
            const result = await this.userService.createUser(req.body);
            res.json(result);
        } catch (error) {
            console.error(error);
            res.status(500).send("Error creating user.");
        }
    }

    @httpPost('/login')
    public async login(req:Request,res:Response){
        try {
            const result = await this.userService.loginUser(req.body);
            console.log(result);
            
            res.json(result);
        } catch (error) {
            console.error(error);
            res.status(500).send("Error login user.");
        }
    }
}